package cc.rboot._core.filter;

import cc.rboot._core.helper.RequestHelper;
import cc.rboot._core.helper.ResponseHelper;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Order(Ordered.HIGHEST_PRECEDENCE)
@Component
@WebFilter(filterName="firstFilter", urlPatterns="/*")
public class RBootFirstFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        RequestHelper.set(request);
        ResponseHelper.set(response);

        try {
            filterChain.doFilter(request, response);
        } finally {
            RequestHelper.remove();
            ResponseHelper.remove();
        }
    }

    @Override
    public void destroy() {

    }
}
